<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Cate;
use Hash;
use Session;
use DB;

class CateController extends Controller
{
    //列表显示
    public function index(Request $request)
    {
    	//读取所有的分类信息
    	$cates = Cate::select(DB::raw('id,name,pid,path,concat(path,",",id) as paths'))->orderBy('paths')->get();

    	//处理$cates变量		
    	foreach($cates as $key=>$value){
    		//获取当前分类的等级
    		$len = count(explode(',',$value->path));
    		$value->name=str_repeat('|------',$len-1).$value->name;
    	}

    	//获取请求参数
    	return view('admin.cate.index',['cates'=>$cates]);
    }

    public function create()
    {
    	//读取分类信息
    	$cates=Cate::get();
    	return view('admin.cate.create',['cates'=>$cates]);
    }

    public function store(Request $request)
    {
    	$cate = new Cate;
    	$cate->name=$request->name;
    	$cate->pid =$request->pid;

    	//检测是否为顶级分类
    	if($cate->pid == 0){
    		$cate->path ='0';
    	}else{
    		$parent = Cate::find($cate->pid);
    		$cate ->path=$parent->path.','.$parent->id;
    	}

    	if($cate->save()){
    		return redirect('/cate')->with('success','执行成功');
    	}
    }

    public function edit($id)
    {
    	$cates = Cate::get();

    	$cate = Cate::findOrFail($id);


    	return view('admin.cate.edit',['cate'=>$cate,'cates'=>$cates]);
    }

    public function update(Request $request,$id)
    {
    	$cate = Cate::findOrFail($id);
    	$cate ->name = $request -> name;
    	$cate ->pid  = $request -> pid;

    	//检测是否为顶级分类
    	if($cate->pid == 0){
    		$cate->path='0';
    	}else{
    		$parent = Cate::find($cate->pid);
    		$cate ->path=$parent->path.','.$parent->id;
    	}

    	if($cate->save()){
    		return redirect('/cate')->with('success','更新成功');
    	}else{
    		return back()->with('error','更新失败');
    	}
    }

    public function destroy($id)
    {
    	$cate = Cate::findOrFail($id);

    	$path=$cate->path.','.$cate->id;

    	Cate::where('path','like',$path.'%')->delete();

    	if($cate->delete()){
    		return back()->with('success','执行成功');
    	}else{
    		return back()->with('error','执行失败');
    	}
    }
}
